package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.constant.MessageConstant;
import com.itheima.entity.Result;
import com.itheima.service.MemberService;
import com.itheima.service.ReportService;
import com.itheima.service.SetMealService;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

@RestController
@RequestMapping("/report")
public class ReportController {
    @Reference
    private MemberService memberService;
    @Reference
    private SetMealService setMealService;
    @Reference
    private ReportService reportService;

    /**
     * 当前月的前12个月会员统计
     *
     * @return
     */
    @RequestMapping("/getMemberReport")
    public Result getMemberReport() {
        try {
            Calendar calendar = Calendar.getInstance();
//       1.得到前12个月的--日期
            calendar.add(Calendar.MONTH, -12);
//       2.获得List集合--前12个月的时间
            List<String> months = new ArrayList<>();
            for (int i = 0; i < 12; i++) {
                calendar.add(Calendar.MONTH, 1);
                months.add(new SimpleDateFormat("yyyy.MM").format(calendar.getTime()));
            }
            HashMap<String, Object> map = new HashMap<>();
            map.put("months", months);
            List<Integer> memberCount = memberService.finMemberCount(months);
            map.put("memberCount", memberCount);
            return new Result(true, MessageConstant.GET_MEMBER_NUMBER_REPORT_SUCCESS, map);
        } catch (Exception e) {
            return new Result(false, MessageConstant.GET_MEMBER_NUMBER_REPORT_FAIL);
        }
    }

    /*
     * 员可以通过移动端自助进行体检预约，在预约时需要选择预约的体检套餐。本章节我们需要通过饼形图直观的展示出会员预约的各     *     个套餐占比情况
     *    /report/getSetmealReport.do
     *    返回json数据格式为data:{setmealNames:['套餐一','套餐二'，'套餐三']
     *                         setmealCount:[{value:number,name:'套餐一'},{value:number,name:'套餐二'}]
     *    }
     */
    @RequestMapping("/getSetmealReport")
    public Result getSetmealReport() {
        try {
            //        1.查找套餐预约人数和预约姓名
            List<Map<String, Object>> setmealCount = setMealService.findOrderCountSetmeal();
            ArrayList<String> setmealNames = new ArrayList<>();
            HashMap<String, Object> datamap = new HashMap<>();
            datamap.put("setmealCount", setmealCount);
            //        2.获取套餐预约名字
            for (Map map : setmealCount) {
                String setmealName = (String) map.get("name");
                setmealNames.add(setmealName);
            }
            datamap.put("setmealNames", setmealNames);
            return new Result(true, MessageConstant.GET_SETMEAL_COUNT_REPORT_SUCCESS, datamap);
        } catch (Exception e) {
            return new Result(false, MessageConstant.GET_SETMEAL_COUNT_REPORT_FAIL);
        }
    }

    /**
     * 通过运营数据统计可以展示出体检机构的运营情况，包括会员数据、预约到诊数据、热门套餐等信息。本章节就是要通过一个表         格的形式来展示这些运营数据
     * /report/getBusinessReportData.do
     * 传输格式：
     * reportData:{
     * reportDate:null,
     * todayNewMember :0,
     * totalMember :0,
     * thisWeekNewMember :0,
     * thisMonthNewMember :0,
     * todayOrderNumber :0,
     * todayVisitsNumber :0,
     * thisWeekOrderNumber :0,
     * thisWeekVisitsNumber :0,
     * thisMonthOrderNumber :0,
     * thisMonthVisitsNumber :0,
     * hotSetmeal :[
     * {name:'阳光爸妈升级肿瘤12项筛查（男女单人）体检套餐',                                                      setmeal_count:200,proportion:0.222},
     * {name:'阳光爸妈升级肿瘤12项筛查体检套餐',setmeal_count:200,proportion:0.222}
     * ]
     * }
     */
    @RequestMapping("/getBusinessReportData")
    public Result getBusinessReportData() {
        try {
            Map<String, Object> datalist = reportService.getBusinessReportData();
            return new Result(true, MessageConstant.GET_MEMBER_NUMBER_REPORT_SUCCESS, datalist);
        } catch (Exception e) {
            return new Result(false, MessageConstant.GET_SETMEAL_COUNT_REPORT_FAIL);
        }
    }


    /**
     * /report/exportBusinessReport.do
     */
    @RequestMapping("/exportBusinessReport")
    public Result exportBusinessReport(HttpServletRequest request, HttpServletResponse response) {
        try {
            Map<String, Object> excelmap = reportService.getBusinessReportData();
//            1.当前日期
            String reportDate = (String) excelmap.get("reportDate");
//            2.今天注册会员
            Integer todayNewMember = (Integer) excelmap.get("todayNewMember");
//            3.全部会员
            Integer totalMember = (Integer) excelmap.get("totalMember");
//            4.本周会员数量
            Integer thisWeekNewMember = (Integer) excelmap.get("thisWeekNewMember");
//            5.本月会员数量
            Integer thisMonthNewMember = (Integer) excelmap.get("thisMonthNewMember");
//            6.今天预约人数--todayOrderNumber
            Integer todayOrderNumber = (Integer) excelmap.get("todayOrderNumber");
//            7.到诊数量-todayVisitsNumber
            Integer todayVisitsNumber = (Integer) excelmap.get("todayVisitsNumber");
//            8.本周预约人数--thisWeekOrderNumber
            Integer thisWeekOrderNumber = (Integer) excelmap.get("thisWeekOrderNumber");
//            9. 本周到诊人数--thisWeekVisitsNumber
            Integer thisWeekVisitsNumber = (Integer) excelmap.get("thisWeekVisitsNumber");
//            10.本月预约人数--thisMonthOrderNumber
            Integer thisMonthOrderNumber = (Integer) excelmap.get("thisMonthOrderNumber");
//            11.本月到诊人数--thisMonthOrderNumber
            Integer thisMonthVisitsNumber = (Integer) excelmap.get("thisMonthVisitsNumber");
//            12.套餐与订单排序
            List<Map<String, Object>> hotSetmeal = (List<Map<String, Object>>) excelmap.get("hotSetmeal");
//

//           得到绝对路径
            String filePath = request.getSession().getServletContext().getRealPath("template") +
                    File.separator + "report_template.xlsx";
//           从内存中读取模板
            XSSFWorkbook workbook = new XSSFWorkbook(new FileInputStream(new File(filePath)));
//            得到表单sheet
            XSSFSheet sheet = workbook.getSheetAt(0);
//             得到表单行数
            XSSFRow row = sheet.getRow(2);
            row.getCell(5).setCellValue(reportDate);//日期

            row = sheet.getRow(4);
            row.getCell(5).setCellValue(todayNewMember);//新增会员数（本日）
            row.getCell(7).setCellValue(totalMember);//总会员数

            row = sheet.getRow(5);
            row.getCell(5).setCellValue(thisWeekNewMember);//本周新增会员数
            row.getCell(7).setCellValue(thisMonthNewMember);//本月新增会员数

            row = sheet.getRow(7);
            row.getCell(5).setCellValue(todayOrderNumber);//今日预约数
            row.getCell(7).setCellValue(todayVisitsNumber);//今日到诊数

            row = sheet.getRow(8);
            row.getCell(5).setCellValue(thisWeekOrderNumber);//本周预约数
            row.getCell(7).setCellValue(thisWeekVisitsNumber);//本周到诊数

            row = sheet.getRow(9);
            row.getCell(5).setCellValue(thisMonthOrderNumber);//本月预约数
            row.getCell(7).setCellValue(thisMonthVisitsNumber);//本月到诊数

            int rownum = 12;
            for (Map map : hotSetmeal) {
                String name = (String) map.get("name");
                long setmeal_count = (long) map.get("setmeal_count");
                BigDecimal proportion = (BigDecimal) map.get("proportion");
                row = sheet.getRow(rownum++);
                row.getCell(4).setCellValue(name);
                row.getCell(5).setCellValue(setmeal_count);
                row.getCell(6).setCellValue(proportion.doubleValue());

            }

            //通过输出流进行文件下载
            ServletOutputStream out = response.getOutputStream();
            response.setContentType("application/vnd.ms-excel");
            response.setHeader("content-Disposition", "attachment;filename=report.xlsx");
            workbook.write(out);

            out.flush();
            out.close();
            workbook.close();

            return null;

        } catch (Exception e) {
            return new Result(false, MessageConstant.GET_BUSINESS_REPORT_FAIL);
        }

    }

    //会员男女比例
    @RequestMapping("/getMamberSexProportionReport")
    public Result getMamberSexProportionReport() {
        try {
            //        1.查找所有会员信息
            List<Map<String, Object>> memberDatas = memberService.findMemberData();

            ArrayList<String> memberSexs = new ArrayList<>();
            HashMap<String, Object> datamap = new HashMap<>();
            for (Map map : memberDatas) {
                String name = (String) map.get("name");
                memberSexs.add(name);
            }
            datamap.put("memberCount", memberDatas);
            datamap.put("memberSex", memberSexs);

            return new Result(true, MessageConstant.GET_SETMEAL_COUNT_REPORT_SUCCESS, datamap);
        } catch (Exception e) {
            return new Result(false, MessageConstant.GET_SETMEAL_COUNT_REPORT_FAIL);
        }
    }

    //会员男女比例
    /*
     * 员可以通过移动端自助进行体检预约，在预约时需要选择预约的体检套餐。本章节我们需要通过饼形图直观的展示出会员预约的各     *     个套餐占比情况
     *    /report/getSetmealReport.do
     *    返回json数据格式为data:{setmealNames:['套餐一','套餐二'，'套餐三']
     *                         setmealCount:[{value:couts,name:'年龄段'},{value:couts2,name:'年龄段2'}]
     *    }
     */

    @RequestMapping("/getMemberAgeReport")
    public Result getMemberAgeReport() throws Exception {

        List<Map<String, Object>> memberAgeCount = memberService.findMemberAge();
        ArrayList<String> memberAges = new ArrayList<>();
        HashMap<String, Object> datamap = new HashMap<>();
        for (Map<String, Object> maps : memberAgeCount) {
            String name = (String) maps.get("name");
            memberAges.add(name);
        }
        datamap.put("memberCount", memberAgeCount);
        datamap.put("memberAges", memberAges);
        return new Result(false,MessageConstant.GET_MEMBER_NUMBER_REPORT_FAIL,datamap);
        }


    }

